#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
logging.basicConfig(level=logging.INFO)
import pdb
import sys
import  shutil 
import  xml.dom.minidom
import tarfile
import datetime


'PC Linux 版本打包脚本，用于批量生成采样版本'
__author__='fengxw'

_this_file_path = os.path.split(os.path.realpath(__file__))[0]
logging.info('this py file in this path:'+_this_file_path)

global _free_key
_free_key=''
global _is_make_sampling
_is_make_sampling='0'
global is_copy_to_top_
is_copy_to_top_='0'
global _build_type
_build_type = 'Release'
global _sanitizer_key
_sanitizer_key = ''



def buildDirs( beBuildDirs ):
	logging.info('buildDirs start ---->')
	for bDir in beBuildDirs:
		if False == os.path.exists(bDir):
			logging.info('dir :'+bDir+' not exists; build it')
			os.mkdir(bDir)
		else:
			logging.info('dir :'+bDir+' already  exists; not do something')
	logging.info('buildDirs end ---->')

def copyFolder(src , dst):
	if True == os.path.exists(dst):
		logging.info('注意：'+dst+' 文件夹已经存在，现在将要删除它！')
		#choice = raw_input('确定要删除 '+dst+' 吗？y/n ?')
		#if 'y' == choice :
			#logging.info('您选择 y ， 那我就删除 '+dst+'啦！不许反悔呦!')
		shutil.rmtree(dst)
		shutil.copytree(src , dst)
		#else:
			#logging.info('您选择：'+choice +' ,那就不删除 '+dst+'啦！')
			#logging.info('打包过程终止！待您手动删除 '+dst+' 之后，再次运行此脚本！')
			#sys.exit()
	else:
		shutil.copytree(src , dst)


def expandDirs( src , dst ):
	logging.info('expandDirs start ---->')
	copyFolder(src , dst)
	logging.info('expandDirs end ---->')


global _bePkgList
_bePkgList = [[]]




def pkg(  pkg_final_name , bePkgList):
	logging.info('pkg start, is:'+pkg_final_name)
	pkg_file = tarfile.open(pkg_final_name , 'w:gz')

	for item in bePkgList:
		pkg_file.add(item[0] , item[1])

	pkg_file.close()
	logging.info('pkg end ---->')

def run( build_type  , is_free , is_make_sampling , is_copy_to_top , is_sanitizer):
	global _this_file_path
	global _free_key
	if('1'==is_free):
		_free_key='_free'
	global _is_make_sampling
	_is_make_sampling = is_make_sampling
	global is_copy_to_top_
	is_copy_to_top_ = is_copy_to_top
	global _build_type
	_build_type = build_type
	global _sanitizer_key
	if('1'==is_sanitizer):
		_sanitizer_key = '_sanitizer'

	logging.info('run start ---->')
	now = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
	pkg_target_path = _this_file_path+ '/' + '../../pkg/' +now

	if(False == os.path.exists(pkg_target_path)):
		os.mkdir(pkg_target_path)


	bePkgList = [
			[pkg_target_path+'/'+_build_type , ''],
			]


	src = pkg_target_path+'/'+ '../../../../../../' + 'Bin/LINUX/X86_64/' + build_type;
	dst = pkg_target_path+'/'+_build_type
	logging.info(" I want to copy mxnavi from path:"+src)
	logging.info(" copy to path:"+dst)
	expandDirs(src , dst );

	
	mxversion = parseMXVersion(build_type)

	pkg_final_name =  pkg_target_path+'/'+mxversion+_sanitizer_key+_free_key+'.tar.gz'
	pkg(pkg_final_name , bePkgList)
	logging.info('PC Linux  普通版本制作完成 ')

	if('1' == is_copy_to_top_):
		copy_to_top(pkg_final_name)

	if('1'==_is_make_sampling):
		logging.info('PC Linux  开始制作采样版本........... ')
		make_sampling_pkg(pkg_target_path , mxversion)
		logging.info('PC Linux  采样版本制作完成 ')


	logging.info('run  end ---->')
	logging.info('恭喜您！成功生成PC Linux版本！运气真的太好啦！')


def parseMXVersion(build_type ):
	targetFilePath = _this_file_path +'/'+ '../../../../../../' + 'Bin/LINUX/ARM_64/'+build_type+'/mxversion.dat'
	logging.info("prase mxversion.dat from path:"+ targetFilePath)
	if False == os.path.exists(targetFilePath):
		logging.error("targetFile:"+targetFilePath +" not exists; exit script" )
		sys.exit()
	else:
		targetFile = open( targetFilePath , "r" )
		if(targetFile):
			lines = targetFile.readlines()
			version_str =  lines[0].strip('\n')
			version_str =  version_str.strip('\r')
			mxversion = version_str.split(":")[2]
			logging.info("obtain mxversion Success! is :"+mxversion)
			return mxversion
		else:
			logging.error("open file:"+targetFilePath+" Failed! exit script")
			sys.exit()
	pass


def make_sampling_pkg(cur_path , mxversion):
	global _this_file_path
	global _free_key
	global _is_make_sampling
	global _build_type
	global _sanitizer_key
	sampling_path = cur_path + '/sampling'
	if(False == os.path.exists(sampling_path)):
		os.mkdir(sampling_path)

	copyFolder(cur_path+'/'+_build_type ,sampling_path+'/'+_build_type) 

	sampling_cfg_path = _this_file_path+'/../../../../config/sampling_cfg'
	#pdb.set_trace()
	for root , dirs , files in  os.walk(sampling_cfg_path , topdown=False):
		for file_item in files:
			logging.info('根据配置文件：'+file_item+' 生成采样版本')
			file_item_key = file_item.split('.')[0]
			file_item_type = file_item.split('.')[1]
			if('json' == file_item_type):
				if(True == os.path.exists( sampling_path+'/'+_build_type+'/tsconfig.json' )):
					os.remove(sampling_path+'/'+_build_type+'/tsconfig.json')
				shutil.copyfile(os.path.join(root ,file_item) , sampling_path+'/'+_build_type+'/tsconfig.json')
				bePkgList = [
					[sampling_path+'/'+_build_type, ''],
					]
				#pdb.set_trace()
				pkg_final_name =  sampling_path+'/'+mxversion+'_'+file_item_key+_sanitizer_key+_free_key+'.tar.gz'
				pkg(pkg_final_name , bePkgList)
				copy_to_top(pkg_final_name)
			else:
				logging.info('不处理扩展名为非json的文件')

def copy_to_top(becopy_file):
	global _this_file_path
	top_path = _this_file_path+'/../../../../../../'+'suy/'
	#pdb.set_trace()
	if(False == os.path.exists(top_path)):
		os.mkdir(top_path)

	top_path += 'LINUX PC/'
	if(False == os.path.exists(top_path)):
		os.mkdir(top_path)
	logging.info('copy file:'+becopy_file+' to top:'+top_path)
	shutil.copy(becopy_file , top_path)


if __name__=='__main__':
	logging.info('argv is:')
	logging.info(sys.argv)
	for i in range(len(sys.argv)):
		if sys.argv[i] == '-build':
			buildDirs()
		elif sys.argv[i] == '-expand':
			expandDirs()
		elif sys.argv[i] == '-pkg':
			pkg()
		elif sys.argv[i] == '-run':
			run( sys.argv[i+1] , sys.argv[i+2], sys.argv[i+3] , sys.argv[i+4] , sys.argv[i+5])
		elif sys.argv[i] == '-extract':
			extract(sys.argv[i+1] , sys.argv[i+2])
		elif sys.argv[i] == '-pm':
			parseMXVersion(sys.argv[i+1])
		elif sys.argv[i] == '-sampling':#编译采样版本
			sampling_pkg(sys.argv[i+1] , sys.argv[i+2])

